import json
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class userSet(viewsets.ViewSet):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_authenticators(self):
        '''重写用户认证'''
        authenticators = []
        if self.request.method == 'GET':
            authenticators = [a() for a in self.authentication_classes]
        return authenticators

    def get_permissions(self):
        '''
        重写权限验证
        '''
        permissions = []
        if self.request.method == 'GET':
            permissions = [p() for p in self.permission_classes]
        return permissions

    def login_user(self, request):
        '''
        用户登录
        '''
        res = {'state': 'success', 'msg': '获取成功', 'data': ''}
        token = ''
        if request.method == 'POST':
            json_str = json.loads(request.body.decode())
            username = json_str.get('username', '')
            user = User.objects.filter(username=username).first()
            if user:
                d = dict(user=user)
                t, _ = Token.objects.update_or_create(d, user=user)
                token = t.key
        res['data'] = token
        return Response(res)

    def check_user(self, request):
        '''
        检测用户
        '''
        res = {'state': 'success', 'msg': '获取成功', 'data': ''}
        username = request.user.username
        res['data'] = username
        return Response(res)
